﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xlit.Project.Entity.Domain;
using Xlit.Project.Service;
using Xlit.Standard.Data;

namespace Xlit.Example.Business.Services
{
    /// <summary>
    ///  角色管理
    /// </summary>
    public class SysRoleService : AppServiceBase
    {
        public IRepository<Sys_Role, int> _SysRoleRepository { get; set; }
        public IRepository<Sys_RoleMenu, int> _SysRoleMenuRepository { get; set; }

        /// <summary>
        ///  获取角色列表
        /// </summary>
        /// <returns></returns>
        public IList<Sys_Role> Get()
        {
            return _SysRoleRepository.GetList();
        }

        /// <summary>
        ///  根据id获取角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Sys_Role Get(int id)
        {
            return _SysRoleRepository.GetEntity(id);
        }

        /// <summary>
        ///  更新角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public int Update(Sys_Role input)
        {
            return _SysRoleRepository.InsertOrUpdate(input);
        }

        /// <summary>
        ///  删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Delete(int id)
        {
            return _SysRoleRepository.Delete(id);
        }

        /// <summary>
        ///  获取角色的菜单权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IList<int> GetMenuPermission(int id)
        {
            return _SysRoleMenuRepository
                .GetList(d => d.RoleId == id)
                .Select(d => d.MenuId)
                .ToList();
        }

        /// <summary>
        /// 保存角色的菜单权限
        /// </summary>
        /// <param name="id">角色id</param>
        /// <param name="checkedId">选中的菜单id集</param>
        /// <returns></returns>
        public int SaveMenuPermission(int id, IList<int> checkedId)
        {
            // 删除该角色关联的菜单权限
            _SysRoleMenuRepository.Delete(d => d.RoleId == id);
            var permissionList = checkedId
                .Select(s => new Sys_RoleMenu
                {
                    MenuId = s,
                    RoleId = id
                });
            // 新添加该角色关联的菜单权限
            return _SysRoleMenuRepository.Insert(permissionList);
        }
    }
}
